﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using SDM.ExamPlanner.BLL;
using SDM.ExamPlanner.DTO;

namespace sdm.exam.ui.ExamAdministration
{

    /// <summary>
    /// Interaction logic for BookExam.xaml
    /// </summary>
    public partial class BookExam : UserControl
    {
        readonly Manager<Classroom> _classroomManager = new Manager<Classroom>();
        readonly Manager<Course> _courseManager = new Manager<Course>();
        readonly Manager<Teacher> _teacherManager = new Manager<Teacher>();
        readonly Manager<Booking> _bookingManager = new Manager<Booking>();

        Dictionary<int, string> _roomDictionary = new Dictionary<int, string>();
        Dictionary<int, string> _roomReservedDictionary = new Dictionary<int, string>();
        Dictionary<int, string> _courseDictionary = new Dictionary<int, string>();
        Dictionary<int, string> _teacherDictionary = new Dictionary<int, string>();
        public BookExam()
        {
            InitializeComponent();
            PopulateList();
            PopulateDropdown();
            PopulateTimeRoller();
        }

        private void PopulateTimeRoller()
        {
            var minutes = new int[60];
            var hours = new int[24];

            for (int hour = 0; hour < 23; hour++)
            {
                hours[hour] = hour + 1;
            }

            for (int minute = 0; minute < 59; minute++)
                minutes[minute] = minute + 1;

            cbbStartHours.DataContext = hours;
            cbbStartMinute.DataContext = minutes;

            cbbEndHour.DataContext = hours;
            cbbEndMinute.DataContext = minutes;
        }

        private void PopulateList()
        {
            _roomReservedDictionary = _bookingManager.Find().ToDictionary(item => item.Id, item => item.Classroom.Name+"("+item.Course.Name+"-->"+item.Teachers.ElementAt(0).Firstname+" "+item.Teachers.ElementAt(0).Lastename+")");
            lstLocations.DataContext = _roomReservedDictionary.Values;
        }

        private void PopulateDropdown()
        {
            //Rooms
            _roomDictionary = _classroomManager.Find().ToDictionary(item => item.Id, item => item.Name);
            cbbClassrooms.DataContext = _roomDictionary.Values;

            //Teachers
            _teacherDictionary = _teacherManager.Find().ToDictionary(item => item.Id,
                                                                     item => item.Firstname + " " + item.Lastename);
            lstTeachers.DataContext = _teacherDictionary.Values;

            //Courses
            _courseDictionary = _courseManager.Find().ToDictionary(item => item.Id, item => item.Name);
            cbbCourses.DataContext = _courseDictionary.Values;

        }

        private void btnAdd_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            KeyValuePair<int, string> classroom = _roomDictionary.FirstOrDefault(c => c.Value.Equals((object)cbbClassrooms.SelectedValue));
            KeyValuePair<int, string> courseSelected = _courseDictionary.FirstOrDefault(c => c.Value.Equals((object)cbbCourses.SelectedValue));
            KeyValuePair<int, string> teacherSelected = _teacherDictionary.FirstOrDefault(c => c.Value.Equals((object)lstTeachers.SelectedValue));
            var startDate = new DateTime();
            var endDate = new DateTime();
            var startHour = (int)cbbStartHours.SelectedValue;
            var startMinute = (int)cbbStartMinute.SelectedValue;
            var endHour = (int)cbbEndHour.SelectedValue;
            var endMinute = (int)cbbEndMinute.SelectedValue;
            if (datePickerStart.SelectedDate != null)
            {
                startDate = datePickerStart.SelectedDate.Value;
            }

            if (datepickerEnd.SelectedDate != null)
            {
                endDate = datepickerEnd.SelectedDate.Value;
            }

            //Make the booking
            Classroom classRoom = _classroomManager.Find().FirstOrDefault(i => i.Id == classroom.Key);
            Course course = _courseManager.Find().FirstOrDefault(i => i.Id == courseSelected.Key);
            Teacher teacher = _teacherManager.Find().FirstOrDefault(i => i.Id == teacherSelected.Key);
            var list = new List<Teacher> {teacher};
            var booking = new Booking
            {
                Classroom = classRoom,
                EndDate = new DateTime(endDate.Year, endDate.Month, endDate.Day, endHour, endMinute, 0),
                StartDate = new DateTime(startDate.Year, startDate.Month, startDate.Day, startHour, startMinute, 0),
                SpecialEquipments = txtEquipment.Text,
                Course = course,
                Teachers = list
            };

            //Checks whether or not the room is already booked.
            var classRoomIsBooked = _bookingManager.Find().FirstOrDefault(cl => cl.Id == classRoom.Id);
            if (classRoomIsBooked != null)
                MessageBox.Show("Exam is already booked.", "Booking duplication", MessageBoxButton.OK,
                                MessageBoxImage.Error);
            else
            {
                _bookingManager.Save(booking);
                MessageBox.Show("Exam is booked.", "Booking success", MessageBoxButton.OK,
                                MessageBoxImage.Information);
            }
        }

        private void lstLocations_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            btnDelete.IsEnabled = lstLocations.SelectedItems.Count > 0;
        }

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            char[] chr = {'('};
            string[] name = lstLocations.SelectedValue.ToString().Split(chr,2);
            string roomName = name[0];
            Classroom classroom = _classroomManager.Find().FirstOrDefault(item => item.Name == roomName);
            _classroomManager.Delete(classroom);

            MessageBox.Show("Exam removed", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
        }
    }
}
